package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"tangzq/shopping/common/model"
	"tangzq/shopping/shop"
	"tangzq/shopping/stock"
	"time"
)

var (
	listenAddr              = flag.String("http", ":9090", "http listen address")
	stockObj   *stock.Stock = stock.NewStock(10)
)

func main() {
	flag.Parse()

	//默认访问
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("welcome to shop!"))
	})

	// 创建订单接口
	http.HandleFunc("/shop/create", Create)

	//打印库存
	go printStock()

	log.Fatal(http.ListenAndServe(*listenAddr, nil))
}

func Create(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	userIdStr := r.Form.Get("userId")
	if userIdStr == "" {
		fmt.Println("用户ID为空")
		return
	}
	userId, err := strconv.Atoi(userIdStr)
	if err != nil {
		fmt.Println(err)
		return
	}

	goodsIdStr := r.Form.Get("goodsId")
	if goodsIdStr == "" {
		fmt.Println("商品ID为空")
		return
	}
	goodsId, err := strconv.Atoi(goodsIdStr)
	if err != nil {
		fmt.Println(err)
		return
	}

	countStr := r.Form.Get("count")
	count, err := strconv.Atoi(countStr)
	if err != nil {
		fmt.Println(err)
		return
	}

	createReq := model.CreateReq{
		UserId:  uint32(userId),
		GoodsId: uint32(goodsId),
		Count:   uint32(count),
	}

	resp, err := shop.Create(createReq, stockObj)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	respJson, _ := json.Marshal(resp)
	w.Header().Add("Content-Type", "application/json")
	fmt.Fprintf(w, string(respJson))
}

func printStock() {
	var during time.Duration = 1e9
	chRate := time.Tick(during)
	for {
		select {
		case <-chRate:
			fmt.Printf("当前库存：%d \n", stockObj.Get())
		}
	}
}


